﻿/**
 * 描述：质保单管理js
 * 创建人：zhunan
 * 日期：2023.8.25
*/
var page = {
  pagetotal: 0,
  pageSize: 12,
  pageNumber: 1,
  mainUrl: getRootPath() + "/Ashx/KeyProcessRecordHandler.ashx",
  type:getParam('type'),
  currentUserInfo: {},
  init: function () {
    page.bind();
    page.initData();
  },
  // 页面事件绑定
  bind: function () {
    $('#grid').datagrid({
      title: '批次数据',
      height: 500,
      remoteSort: false,
      rownumbers: true,
      nowrap: false,
      fitColumns: true,
      singleSelect: true,
      columns: [[
        // { field: "check", checkbox: "true" },
        { field: 'mfgordername', title: '生产订单号', width: 140 },
        { field: 'togetherflag', title: '件号/批次号', width: 100 },
        { field: 'status', title: '批次状态', width: 80 },
        { field: 'ckstatus', title: '确认状态', width: 80 },
        { field: 'factoryname', title: '承制单位', width: 100 },
        {
          field: 'instoredate', title: '入库时间', width: 100,
          formatter: function (value, row, index) {
            return value ? value.split('T')[0] : value;
          }
        },
        { field: 'planqty', title: '计划数', width: 80 },
        { field: 'wipqty', title: '在制总数', width: 80 },
        { field: 'workflowstepname', title: '当前工序', width: 100 },
        { field: 'specno', title: '工序号', width: 80 },
        { field: 'containertypename', title: '批次卡类型', width: 100 },
        {
          field: 'plannedstartdate', title: '计划开始', width: 100,
          formatter: function (value, row, index) {
            return value ? value.split('T')[0] : value;
          }
        },
        {
          field: 'plannedcompletiondate', title: '计划完成', width: 100,
          formatter: function (value, row, index) {
            return value ? value.split('T')[0] : value;
          }
        }
      ]],
      view: detailview,
      detailFormatter: function (index, row) {
        return '<div style="padding:5px;"><table class="ddv"></table></div>';
      },
      onCheck: function (rowIndex, rowData) { },
      onClickCell: function (rowIndex, field, value) {
        if (field !== '_expander') {
          $('#grid').datagrid('expandRow', rowIndex);// 展开所选行
          var row = $("#grid").datagrid("getRows");// 获取主表格的所有行对象
          for (var i = 0; i < row.length; i++) {
            if (i !== rowIndex) {
              $("#grid").datagrid("collapseRow", i);// 折叠其他行
            }
          }
        }
      },
      onExpandRow: function (index, row) {
        ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
        ddv.datagrid({
          url: page.mainUrl + '?actions=getContainerInfo',
          rownumbers: true,
          loadMsg: '加载中，请稍后...',
          nowrap: true,
          queryParams: { action: "getContainerInfo", togetherflag: row.togetherflag,printType:page.type },
          method: 'POST',
          columns: [[
            { field: "check", checkbox: "true" },
            { field: 'containerid', title: 'containerid', width: 200, hidden: true },
            { field: 'workflowid', title: 'workflowid', width: 200, hidden: true },
            { field: 'containername', title: '流水卡号', width: 300 },
            { field: 'teamname', title: '班组', width: 100 },
            { field: 'qty', title: '在制数', width: 60 },
            { field: 'status', title: '确认状态', width: 80 },
            { field: 'techemp', title: '技术员', width: 60 },
            {
              field: 'techconfirmdate', title: '技术员确认日期', width: 100,
              formatter: function (value, row, index) {
                return value ? value.split('T')[0] : value;
              }
            },
            { field: 'techconfirmnote', title: '技术员确认备注', width: 100 },
            { field: 'checkemp', title: '检验员', width: 80 },
            {
              field: 'checkconfirmdate', title: '检验确认日期', width: 100,
              formatter: function (value, row, index) {
                return value ? value.split('T')[0] : value;
              }
            },
            { field: 'checkconfirmnote', title: '检验确认备注', width: 100 },
            { field: 'spindlenode', title: '锭节点', width: 100 },
            { field: 'containertechemp', title: '工艺员', width: 80 }
          ]],
          onResize: function () {
            $('#grid').datagrid('fixDetailRowHeight', index);//固定明细行的高度。
          },
          onLoadSuccess: function (data) {
            setTimeout(function () {
              $('#grid').datagrid('fixDetailRowHeight', index);//固定明细行的高度。
            }, 0);
            ddv.datagrid('selectAll');
          }
        });

      },
      onLoadSuccess: function (data) {
        $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
          total: page.pagetotal,
          pageSize: page.pageSize,
          pageNumber: page.pageNumber
        });
        customizedEasyuiPagination('pp'); //定制化分页
      },
      // 行点击事件
      onClickRow: function (rowIndex, rowData) { }
    });

    //批次表格分页
    $('#pp').pagination({
      onSelectPage: function (pageNumber, pageSize) {
        customizedEasyuiPagination('pp'); //定制化分页
        page.pageSize = pageSize;
        page.pageNumber = pageNumber;
        page.search();
      }
    });

    //绑定分页go按钮
    $(function () {
      $('#pageGo').on("click", function () {
        var pageNumber = $(this).parents('tr').find('.pagination-num').val();
        page.pageNumber = pageNumber;
        page.search();
      });
    });

    // 查询
    $("#btnSearch").on("click", function () {
      page.pageNumber = 1;
      page.search();
    });

    // 重置按钮
    $('#btnReset').on("click", function () {
      page.resetData();
    });

    //导出按钮
    $('#btnExport').on("click", function (){
        page.export();
    });
    // 技术确认--打开弹窗
    $("#teachConfirm").on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      page.getTeachOrCheckConfirmData(selectedData);
      $('#teachConfirmDialog').window('open');
      $('#txtTeachEmployee').textbox('setValue', page.currentUserInfo.fullname);
    });

    // 技术确认--关闭弹窗
    $("#teachConfirmClose").on("click", function () {
      $('#teachConfirmDialog').window('close');
    });

    // 检验确认--打开弹窗
    $("#checkConfirm").on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      page.getTeachOrCheckConfirmData(selectedData);
      $('#checkConfirmDialog').window('open');
      $('#txtCheckEmployee').textbox('setValue', page.currentUserInfo.fullname);
    });

    // 检验确认--关闭弹窗
    $("#checkConfirmClose").on("click", function () {
      $('#checkConfirmDialog').window('close');
    });

    // 技术确认--点击保存
    $('#teachConfirmSave').on("click", function () {
      var selectedData = page.getSelection();
      page.saveTeachConfirmData(selectedData);
    });

    // 检验确认--点击保存
    $('#checkConfirmSave').on("click", function () {
      var selectedData = page.getSelection();
      page.saveCheckConfirmData(selectedData);
    });

    // 移除技术确认
    $('#teachConfirmCancel').on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      $.messager.confirm('移除前确认', '你确定要移除技术确认数据吗?', function (r) {
        // 确认删除
        if (r) { page.removeTeachConfirmData(selectedData); }
      });
    });

    // 移除检验确认
    $('#checkConfirmCancel').on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      $.messager.confirm('移除前确认', '你确定要移除检验确认数据吗?', function (r) {
        // 确认删除
        if (r) { page.removeCheckConfirmData(selectedData); }
      });
    });

    // 质保单打印
    $('#print').on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      page.savePrintSession(selectedData,0);
    });
     // 振动攻关打印
    $('#zdggPrint').on("click", function () {
      var selectedData = page.getSelection();
      if (selectedData.length === 0) { return; }
      page.savePrintSession(selectedData,1);
    });
    if(page.type=='1'){$('#zdggPrint').show();$('#print,#teachConfirm,#checkConfirm,#teachConfirmCancel,#checkConfirmCancel').hide();} 
    else{$('#print,#teachConfirm,#checkConfirm,#teachConfirmCancel,#checkConfirmCancel').show();$('#zdggPrint').hide();}
  },
  //初始化页面
  initData: function () {
    page.getCurrentUserInfo();
  },
  // 查询
  search: function (pageNumber) {
    $('#grid').datagrid('loadData', []);
    var formData = {
      action: "getData",
      factoryid: $('#ddlFactory').combobox('getValue'),
      scanContainerName: $('#txtScanContainer').textbox('getValue'),
      mfgordername: $('#txtScanOrder').textbox('getValue'),
      productname: $('#txtProduct').textbox('getValue'),
      togetherflag: $('#txtContainer').textbox('getValue'),
      specno: $('#txtSpecNo').textbox('getValue'),
      instoredatestart: $('#txtInstoreDateStart').datebox('getValue'),
      instoredateend: $('#txtInstoreDateEnd').datebox('getValue'),
      // ddlType: $('#ddlType').combobox('getValue'),
      ddlContainerStatus: $('#ddlContainerStatus').combobox('getValue'),
      ddlConfirmStatus: $('#ddlConfirmStatus').combobox('getValue'),
//      workflowEmpName: $('#txtWorkflowEmpName').textbox('getValue'),
      printType:page.type,//打印类别（1:振动攻关，其他：质保单）
      pageSize: page.pageSize,
      pageNumber: pageNumber || page.pageNumber
    };

    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=getData",
      data: formData,
      cashe: false,
      async: true,
      beforeSend: function () {
        $('#grid').datagrid('loading');
        $(this).attr("disabled", "disabled"); //禁用按钮
      },
      success: function (data) {
        $('#grid').datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        var result = JSON.parse(data);
        if (result.Result) {
          //给分页对象赋值
          page.pagetotal = result.RowCount;
          $('#grid').datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $('#grid').datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        alert(XMLHttpRequest.responseText);
      }
    });
  },
  // 导出 add by zhangrj 20251016
  export: function () {
    var formData = {
      action: "exportData",
      factoryid: $('#ddlFactory').combobox('getValue'),
      scanContainerName: $('#txtScanContainer').textbox('getValue'),
      mfgordername: $('#txtScanOrder').textbox('getValue'),
      productname: $('#txtProduct').textbox('getValue'),
      togetherflag: $('#txtContainer').textbox('getValue'),
      specno: $('#txtSpecNo').textbox('getValue'),
      instoredatestart: $('#txtInstoreDateStart').datebox('getValue'),
      instoredateend: $('#txtInstoreDateEnd').datebox('getValue'),
      // ddlType: $('#ddlType').combobox('getValue'),
      ddlContainerStatus: $('#ddlContainerStatus').combobox('getValue'),
      ddlConfirmStatus: $('#ddlConfirmStatus').combobox('getValue'),
//      workflowEmpName: $('#txtWorkflowEmpName').textbox('getValue'),
      printType:page.type//打印类别（1:振动攻关，其他：质保单）
    };
    FileDownLoad(page.mainUrl, formData);//导出
  },
  // 重置
  resetData: function () {
    page.pageNumber = 1;
    clearMessage();
    clearEasyuiDataGrid("grid"); //清空列表
    $('#txtScanContainer').textbox('setValue', '');
    $('#txtScanOrder').textbox('setValue', '');
    $('#txtProduct').textbox('setValue', '');
    $('#txtContainer').textbox('setValue', '');
    $('#txtSpecNo').textbox('setValue', '');
    $('#txtInstoreDateStart').datebox('setValue', '');
    $('#txtInstoreDateEnd').datebox('setValue', '');
    // $('#ddlType').combobox('select', '关键过程');
    $('#ddlContainerStatus').combobox('select', '');
    $('#ddlConfirmStatus').combobox('select', '');
  },
  // 获取当前用户信息
  getCurrentUserInfo: function () {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=getCurrentUserInfo",
      data: { action: "getCurrentUserInfo", },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          var dataObj = result.DBTable[0];
          page.currentUserInfo = {
            employeeid: dataObj.employeeid,
            fullname: dataObj.fullname,
            factoryid: dataObj.factoryid
          };
          page.getFactory();
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 获取页面中所选流水卡
  getSelection: function () {
    var datas = $("#grid").datagrid('getChecked');
    var index = $("#grid").datagrid('getRowIndex', datas[0]);
    if (datas.length === 0) {
      alert('请选择批次');
      return [];
    }

    var selectedData = $("#grid").datagrid('getRowDetail', index).find('table.ddv').datagrid("getSelections");
    if (selectedData.length === 0) {
      alert('请选择流水卡');
      return [];
    }
    return selectedData;
  },
  // 保存技术员确认数据
  saveTeachConfirmData: function (selectedData) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=saveTeachConfirmData",
      data: {
        action: "saveTeachConfirmData",
        selectedData: JSON.stringify(selectedData),
        techconfirmemployee: page.currentUserInfo.employeeid,
        techconfirmdate: $('#txtTeachConfirmDate').datebox('getValue'),
        techconfirmnote: $('#txtTeachConfirmNote').textbox('getValue')
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          displayMessage('保存成功!', true);
          $('#teachConfirmDialog').window('close');
          page.search();
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 保存检验确认数据
  saveCheckConfirmData: function (selectedData) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=saveCheckConfirmData",
      data: {
        action: "saveCheckConfirmData",
        selectedData: JSON.stringify(selectedData),
        checkconfirmemployee: page.currentUserInfo.employeeid,
        checkconfirmdate: $('#txtCheckConfirmDate').datebox('getValue'),
        checkconfirmnote: $('#txtCheckConfirmNote').textbox('getValue'),
        spindlenode: $('#txtSpindleNode').textbox('getValue'),
        groupname: $('#txtGroupname').textbox('getValue')
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          displayMessage('保存成功!', true);
          $('#checkConfirmDialog').window('close');
          page.search();
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 移除技术确认
  removeTeachConfirmData: function (selectedData) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=removeTeachConfirmData",
      data: {
        action: "removeTeachConfirmData",
        selectedData: JSON.stringify(selectedData)
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          displayMessage('移除成功!', true);
          page.search();
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 移除检验确认
  removeCheckConfirmData: function (selectedData) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=removeCheckConfirmData",
      data: {
        action: "removeCheckConfirmData",
        selectedData: JSON.stringify(selectedData)
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          displayMessage('移除成功!', true);
          page.search();
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 查询技术员、检验员确认已维护数据
  getTeachOrCheckConfirmData: function (selectedData) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=getTeachOrCheckConfirmData",
      data: {
        action: "getTeachOrCheckConfirmData",
        selectedData: JSON.stringify(selectedData)
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          var dataObj = result.DBTable.length > 0 ? result.DBTable[0] : {};
          var techconfirmdate = dataObj.techconfirmdate ? dataObj.techconfirmdate.split('T')[0] : '';
          var checkconfirmdate = dataObj.checkconfirmdate ? dataObj.checkconfirmdate.split('T')[0] : '';
          $('#txtTeachConfirmDate').datebox('setValue', techconfirmdate);
          $('#txtTeachConfirmNote').textbox('setValue', dataObj.techconfirmnote);
          $('#txtCheckConfirmDate').datebox('setValue', checkconfirmdate);
          $('#txtSpindleNode').textbox('setValue', dataObj.spindlenode);
          $('#txtCheckConfirmNote').textbox('setValue', dataObj.checkconfirmnote);
          $('#txtGroupname').textbox('setValue', dataObj.groupname);
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  },
  // 获取分厂列表
  getFactory: function () {
    $.ajax({
      url: page.mainUrl + "?actions=getFactory",
      data: { action: "getFactory" },
      type: "post",
      cashe: false,
      dataType: 'json',
      success: function (res) { //ajax成功后
        if (res.Result) {
          res.DBTable.unshift({ factoryid: '', factoryname: '全部' });
          $("#ddlFactory").combobox({
            valueField: 'factoryid',
            textField: 'factoryname',
            panelHeight: 200,
            data: res.DBTable, //下拉数据
          });
//          if (page.currentUserInfo.factoryid) {
//            $("#ddlFactory").combobox('select', page.currentUserInfo.factoryid);
//            $("#ddlFactory").combobox('disable');
//          }
        } else {
          displayMessage(res.Message, res.Result);
        }
      }
    });
  },
  savePrintSession: function (selectedData,type) {
    $.ajax({
      type: "Post",
      url: page.mainUrl + "?actions=savePrintSession",
      data: {
        action: "savePrintSession",
        selectedData: JSON.stringify(selectedData)
      },
      cashe: false,
      async: true,
      beforeSend: function () { },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          window.open('ContainerWarrantyPrintPopupForm.aspx?type='+type+'&v=' + new Date().getTime());
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (xhr) {
        alert(xhr.responseText);
      }
    });
  }

};
page.init();

$(function () {
  //扫描批次事件
  $('#txtScanContainer').textbox({
    onChange: function (n, o) {
      page.pageNumber = 1;
      page.search();
    }
  });

  //订单扫描事件
  $('#txtScanOrder').textbox({
    onChange: function (n, o) {
      page.pageNumber = 1;
      page.search();
    }
  });
})